package cn.hml.user.service.impl;

import cn.hml.basic.exception.BusinessException;

import cn.hml.basic.util.Md5Utils;
import cn.hml.basic.util.StrUtils;
import cn.hml.org.domain.Employee;
import cn.hml.user.domain.Logininfo;
import cn.hml.user.domain.User;
import cn.hml.user.mapper.LogininfoMapper;
import cn.hml.user.mapper.UserMapper;
import cn.hml.user.service.IUserService;
import cn.hml.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String confirmPwd = map.get("confirmPwd");
        //校验空值
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(password)||StringUtils.isEmpty(confirmPwd)){
            throw new BusinessException("信息不能为空");
        }
        //二：校验 - 密码是否一致
        if (!password.equals(confirmPwd)){
            throw new BusinessException("两次密码不一致");
        }
        //三：校验 - 手机验证码是否过期，是否正确 [9555:4545455454545]
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj==null){
            throw new BusinessException("验证码已过期");

        }
        if (!obj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("验证码错误");
        }
        //四：添加到数据库，密码加密加盐
        User user=map2User(phone,password);
        Logininfo logininfo=user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.sava(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.sava(user);


    }

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String password = map.get("password");
        String confirmPwd = map.get("confirmPwd");
        String email = map.get("email");
        //校验空值
        if (StringUtils.isEmpty(password)||StringUtils.isEmpty(confirmPwd)||StringUtils.isEmpty(email)){
            throw new BusinessException("信息不能为空");
        }
        //校验密码是否一致
        if (!password.equals(confirmPwd)){
            throw new BusinessException("两次密码不一致");
        }
        //四：添加到数据库，密码加密加盐
        User user=map2User(email,password);
        user.setPhone(null);
        user.setEmail(email);
        user.setState(0);
        Logininfo logininfo=user2Logininfo(user);
        logininfo.setDisable(false);
        //1.先添加t_logininfo
        logininfoMapper.sava(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.sava(user);
        //发邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        //发送复杂邮件的工具类
        //true - 能够添加附件
        mimeMessageHelper.setFrom("2667454104@qq.com");
        mimeMessageHelper.setSubject("账号激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        mimeMessageHelper.setText("<h1>你的账号已经注册!!!</h1><a href='http://127.0.0.1:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",
                true);
        //收件人
        mimeMessageHelper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void active(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);


    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User map2User(String phone, String password) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        password = Md5Utils.encrypByMd5(password + salt);
        user.setPassword(password);
        user.setSalt(salt);
        user.setState(1);
        return user;
    }
    @Override
    @Transactional
    public void sava(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.sava(logininfo);//获取到自增ID

        //添加user的数据
        user.setLogininfoId(logininfo.getId());
        super.sava(user);
    }
    @Override
    @Transactional
    public void del(Long id) {
        //先查询登陆信息id
        User user = userMapper.loadById(id);

        //删除user
        super.del(id);

        //删除logininfo
        logininfoMapper.del(user.getLogininfoId());
    }
    @Override
    @Transactional
    public void update(User user) {//前端传过来的user是没有登陆信息id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        User oldUser = userMapper.loadById(user.getId());//loginfo_id

        //修改user信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //修改登陆信息
        Logininfo oldLogininfo = logininfoMapper.loadById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //设置会以前的id - 进行修改
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }
}
